app.controller('TagOneCtrl', ['$scope', '$timeout', '$http', '$compile', 'toaster', '$location', '$modal', 'R', 'FileUploader', '$q', '$rootScope',
function($scope, $timeout, $http, $compile, toaster, $location, $modal, R, FileUploader, $q, $rootScope) {
    
    var urlparams = $location.search();
    $scope.id = urlparams.id;
    $scope.oriorder = 0;
    $scope.oritype = 0;

    if ($scope.id) {
    	$scope.item = $rootScope.getSgObj('TAGONE');
    	$scope.oriorder = $scope.item.order;
    	$scope.oritype = $scope.item.type;
    
    	if (!$scope.item){
            $location.url("/app/tag/list");
    	}
    }else{
        $scope.item = {
            tagName: '',
            order: 0,
            type: 0
        }
    }

    $scope.mappers = {
        order: [{
            'id': 0,
            'name': '不推荐'
        }],
        type:  [{
            'id': 0,
            'name': '产品/需求'
        },{
            'id': 1,
            'name': '用户标签'
        }]
    }

    $scope.$watch('item.type', function(type){
    	if (type != $scope.oritype){
    		$scope.item.order = 0;
    	}else{
    		$scope.item.order = $scope.oriorder;
    	}

    	if (type == 0){
    		var rtype = 2;
    	}
    	if (type == 1){
    		var rtype = 3;
    	}

		R.getRecomandIndex({type: rtype}).then(function(data){
		    $scope.mappers.order = [{
		    	id: 0,
		    	name: '不推荐'
		    }];
		    var exist = 0;
		    for (var i = 0; i<data.bizData.length; i++){
		    	$scope.mappers.order.push({
		    		id: data.bizData[i],
		    		name: data.bizData[i]
		    	});
		    	if (data.bizData[i] == $scope.item.order){
		    		exist = 1;
		    	}
		    }
		    if (!exist){
		    	$scope.mappers.order.push({
		    		id: $scope.item.order,
		    		name: $scope.item.order
		    	});
		    }
		});
    });

    $scope.uploader = new FileUploader({
        url: R.getFileUpload(),
        formData: [{
            type: 0
        }],
        autoUpload: true,
        alias: 'inputFile'
    });

    $scope.opened = [];
    $scope.open = function($event,index) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.opened[index] = true;
    };

    $scope.submit = function(){
        if ($scope.item.id){
            R.updateTag($scope.item).then(function(data){
                toaster.success("操作成功");
                $location.url("/app/tag/list");
            });
        }else{
			var user = $rootScope.getSgObj('LOGINUSER');
          
            $scope.item.userId = user.id;
           
            R.addTag($scope.item).then(function(data){
                toaster.success("操作成功");
                $location.url("/app/tag/list");
            });
        }
    }

}]);